package api

import (
	"bbs-go/internal/models/constants"

	"github.com/kataras/iris/v12"
	"github.com/mlogclub/simple/sqls"
	"github.com/mlogclub/simple/web"
	"github.com/mlogclub/simple/web/params"

	"bbs-go/internal/models"
	"bbs-go/internal/services"
)

type CategoryController struct {
	Ctx iris.Context
}

func (c *CategoryController) GetBy(id int64) *web.JsonResult {
	category := services.CategoryService.Get(id)
	if category == nil || category.Status == constants.StatusDeleted {
		return web.JsonErrorMsg("数据不存在")
	}
	return web.JsonData(c.buildCategory(*category))
}

// 列表
func (c *CategoryController) GetList() *web.JsonResult {
	categorys := services.CategoryService.Find(sqls.NewCnd().Asc("id"))

	var itemList []map[string]interface{}
	for _, v := range categorys {
		itemList = append(itemList, c.buildCategory(v))
	}
	return web.JsonData(itemList)
}

// 列表
func (c *CategoryController) GetCategorys() *web.JsonResult {
	page := params.FormValueIntDefault(c.Ctx, "page", 1)
	categorys, paging := services.CategoryService.FindPageByCnd(sqls.NewCnd().
		Eq("status", constants.StatusOk).Page(page, 20).Asc("id"))

	var itemList []map[string]interface{}
	for _, v := range categorys {
		itemList = append(itemList, c.buildCategory(v))
	}
	return web.JsonPageData(itemList, paging)
}

// 前10个链接
func (c *CategoryController) GetTopCategorys() *web.JsonResult {
	categorys := services.CategoryService.Find(sqls.NewCnd().
		Eq("status", constants.StatusOk).Limit(10).Asc("id"))

	var itemList []map[string]interface{}
	for _, v := range categorys {
		itemList = append(itemList, c.buildCategory(v))
	}
	return web.JsonData(itemList)
}

func (c *CategoryController) buildCategory(category models.Category) map[string]interface{} {
	return map[string]interface{}{
		"id":         category.Id,
		"name":      category.Name,
		"status":       category.Status,
		"createTime": category.CreateTime,
	}
}
